package com.sita.redsun.other.test;

import com.google.common.io.BaseEncoding;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Date;

/**
 * Created by wangzhebin on 16/12/2.
 */
public class ReciveThread extends  Thread {

    private boolean flag;
    private Socket socket;
    private int logflag;

    public int getLogflag() {
        return logflag;
    }

    public void setLogflag(int logflag) {
        this.logflag = logflag;
    }

    public ReciveThread() {
        flag = true;
        logflag=1;
    }

    public void run() {

        System.out.println(new Date().toString());

        while (flag) {
            byte[] datas = new byte[256];
            //socket.getInputStream().read(datas);
            InputStream ii = null;
            if (!socket.isConnected()){
                /*try {
                    socket.close();
                    flag=false;
                    System.out.println("已经关闭");
                    break;

                } catch (IOException e) {
                    e.printStackTrace();
                }*/
            }
            try {
                ii = socket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                ii.read(datas);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String bb= BaseEncoding.base16().encode(datas);
            //if (logflag==1) {
                System.out.println(new Date().toString());
                System.out.println("收到"+bb);
                if (bb.substring(0,30).equals("000000000000000000000000000000")){
                    try {
                        boolean a=socket.getKeepAlive();

                        socket.close();
                        flag=false;
                        System.out.println("已经关闭");
                        break;

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            //}
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
        System.out.println(new Date().toString());
    }

    public Socket getSocket() {
        return socket;
    }

    public ReciveThread setSocket(Socket socket) {
        this.socket = socket;
        flag=true;
        return this;
    }
}
